(function (window, undefined) {

    var SOURCE = '__cnnit-navigation__'
  
    /**
     * 导航方法
     * @param {VueRouter} router vue router 对象
     */
    function Navigation(router, global) {
      this.router = router
      this.global = global || window.parent
    }
  
    Navigation.prototype.openLink = function (opts) {
      this.sendMessage('open', {
        title: opts.title,
        path: opts.link
      })
    }
  
    /**
     * 
     * @param {VueRouterLocation} opts vue router 的配置对象
     */
    Navigation.prototype.open = function (opts) {
      var resolve = this.router.resolve(opts)
  
      var origin = location.origin
      var pathname = location.pathname || '/'
  
      this.sendMessage('open', {
        title: opts.title,
        path: origin + pathname + resolve.href
      })
    }
  
    Navigation.prototype.close = function () {
      this.sendMessage('close')
    }
  
    Navigation.prototype.sendMessage = function (type, payload) {
      if (!type) throw new Error('请传入 type ！')
  
      var strData = { source: SOURCE, type, payload }
  
      this.global.postMessage(strData, '*')
    }
  
  
   
  
    window.cnnitNavigation = {
      register(router, global) {
        return new Navigation(router, global)
      },
      listener(handlerMap) {
        function onMessage(e) {
          var data = e.data || {}
      
          if (data && data.source !== SOURCE) return
      
          handlerMap[data.type] && handlerMap[data.type](data.payload)
        }
  
        window.addEventListener('message', onMessage, false)
  
  
        return () => {
          window.removeEventListener('message', onMessage)
        }
      }
    }
  })(window)